package server

import (
	"fmt"
	"net"
	"time"
)

//connet 与服务端的链接
var connet *net.TCPConn

//Client 客户端程序
type Client struct {
	Port string
	Host string
}

//NewClient 创建客服端程序
func NewClient(Port, Host string) *Client {
	return &Client{
		Port: Port,
		Host: Host,
	}
}

// WiteString 获取可使用的链接
func WiteString(data string) error {
	if connet == nil {
		return fmt.Errorf("%s", "为获取到链接")
	}
	connet.Write([]byte(data))
	return nil
}

//Connet 链接指定地址端口服务
func (c *Client) Connet() {
	//for {
	addr := fmt.Sprintf("%s:%s", c.Host, c.Port)
	for {
		//生成TCP地址链接
		tcpAddr, _ := net.ResolveTCPAddr("tcp4", addr)
		conn, err0 := net.DialTCP("tcp", nil, tcpAddr)
		if err0 != nil {
			fmt.Println(fmt.Sprintf("链接服务端:[%s]:%s", addr, "出现错误"), err0)
		} else {
			connet = conn
			beatHert(conn)
		}
		time.Sleep(time.Second * 3)
	}
}
func beatHert(conn *net.TCPConn) {
	for {
		len, err := conn.Write([]byte("0000"))
		//打印出数据
		if err == nil {
			fmt.Println("client", "发送心跳包", len)
		} else {
			fmt.Println("client", "链接服务端发现：无法链接", err)
			conn.Close()
			break
		}
		time.Sleep(time.Duration(5) * time.Second)
	}
}
